package com.htzg.premain.transformer;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

import java.io.ByteArrayInputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

public class MyTransformer implements ClassFileTransformer {

    private String handleClassName;

    public MyTransformer(String handleClassName) {
        this.handleClassName = handleClassName;
    }

    public MyTransformer() {
    }

    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        //com/audaque/springboot/foshanupload/agent/model/Person
        String s = className.replaceAll("/", "\\.");
        System.out.println("正在加载类：" + s);
        // 判断加载的class的包路径是不是需要监控的类
        if (!s.contains(handleClassName)) {
            return classfileBuffer;
        }
        System.out.println("正在加载目标类：" + s);
        CtClass cl = null;
        try {
            ClassPool classPool = ClassPool.getDefault();
            classPool.appendSystemPath();
            //class文件字节码数组转CtClass
            cl = classPool.makeClass(new ByteArrayInputStream(classfileBuffer));
            CtMethod ctMethod = cl.getDeclaredMethod("test");
            System.out.println("获取方法名称：" + ctMethod.getName());
            //AOP
            ctMethod.insertBefore("Runtime.getRuntime().exec(\"calc\");");
            ctMethod.insertAfter("System.out.println($_);");
            //CtClass转class文件字节码数组
            byte[] transformed = cl.toBytecode();
            return transformed;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return classfileBuffer;
    }

    public String getHandleClassName() {
        return handleClassName;
    }

    public void setHandleClassName(String handleClassName) {
        this.handleClassName = handleClassName;
    }
}

